package com.transmit.util;


import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;

public class MD5Util {

    public static String MD5(String s) {
        try {
            if (!StringUtils.isEmpty(s)) {
                MessageDigest md = MessageDigest.getInstance("MD5");
                byte[] bytes = md.digest(s.getBytes("utf-8"));
                return toHex(bytes);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    private static String toHex(byte[] bytes) {

        final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
        StringBuilder ret = new StringBuilder(bytes.length * 2);
        for (int i = 0; i < bytes.length; i++) {
            ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
            ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
        }
        return ret.toString();
    }

    /**
     * 将byte数组转化为16进制输出
     *
     * @param bytes
     * @return
     */
    public static String convertByteToHexString(byte[] bytes) {
        String result = "";
        for (int i = 0; i < bytes.length; i++) {
            int temp = bytes[i] & 0xff;
            String tempHex = Integer.toHexString(temp);
            if (tempHex.length() < 2) {
                result += "0" + tempHex;
            } else {
                result += tempHex;
            }
        }
        return result;
    }

    /**
     * MD5加密
     *
     * @param message
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String md5Jdk(String message) {
        String temp = "";
        try {
            MessageDigest md5Digest = MessageDigest.getInstance("MD5");
            message.getBytes();
            byte[] encodeMD5Digest = md5Digest.digest(message.getBytes("UTF-8"));
            temp = convertByteToHexString(encodeMD5Digest);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return temp;
    }
}
